/**
 * 适配win版本和apicloud支持的移动版本模块
 * @author <jhua.zuo@baisonmail.com>
 */
if(isPC){
    //electron核心的外壳适配
    var os = nodeRequire('os');
    switch(os.type()){
        case "Windows_NT":
        case "Linux":
        case "Darwin":
            var db; 
            var fs = nodeRequire('fs');
            var sqlite3 = nodeRequire('sqlite3').verbose();
            var serialNumber = nodeRequire('serial-number');
            var printer = nodeRequire('printer');
            var ipcRenderer = nodeRequire('electron').ipcRenderer;
            //去掉监听事件的最大限制
            ipcRenderer.setMaxListeners(0);
            var iconv = nodeRequire('iconv-lite');
            const shell = nodeRequire('electron').shell;
            //PC版本语言包适配
            var l = $api.getStorage('language');
            if (l == undefined || l == '') {
                var l = 'zh_cn';
            }
            var lang = nodeRequire('./language/'+l+'.json');
            
            var electron_dialog = nodeRequire('electron').remote.dialog;
            //console.log(lang);
            /**
            ipcRenderer.on('global-shortcut', function (event, message) {
                alert(message);
            });
                */
            /*****
            printer.printDirect({data:'testprinter'
                , type: 'TEXT' // type: RAW, TEXT, PDF, JPEG, .. depends on platform
                , success:function(jobID){
                    console.log("sent to printer with ID: "+jobID);
                }
                , error:function(err){console.log(err);}
            });
            *****/
            
            //console.log(nodeRequire('remote').getGlobal('sharedObject').someProperty);
            var baison_app = {};
            baison_app.api = {};
            baison_app.fs = {};
            baison_app.db = {};
            baison_app.citySelector = {};
            baison_app.printmodule = baison_app.usbPrint = {};
            baison_app.scanner = {};
            
            serialNumber.preferUUID = true;
            baison_app.api.screenWidth = window.screen.width;
            baison_app.api.screenHeight = window.screen.height;
            baison_app.api.systemType = os.type();
            baison_app.api.deviceModel = os.platform() + ' ' + os.release();
            //console.log(os);
            
            baison_app.api.fsDir = __dirname;

            serialNumber(function (err, value) {
                baison_app.api.deviceId = value;
            });
            
            //适配api对象基本方法和属性 =================================================
            baison_app.api.toLauncher = function(){
                process.exit(0);
            };
            
            baison_app.api.addEventListener = function(){
                //TODO
            };
            
            //图片打开模块 =============================================================
            baison_app.api.getPicture = function(params,callback){
                electron_dialog.showOpenDialog({
                    properties: ['openFile'],
                    filters:[{name: 'Images', extensions: ['jpg', 'png', 'gif'] }]
                },function(e){
                    if(e&&e.length>0){
                        callback({
                            'data':e[0],
                            'base64Data':'',
                            'duration':0
                        },{});
                    }else{
                        callback({},{'msg':'NO_DATA_SELECTED'});
                    }
                });
            };
            //二维码处理 =============================================================
            var qr = nodeRequire('qr-image');
            baison_app.scanner.encode = function(params,callback){
                var path;
                //生成二维码
                path = __dirname + "/barImage/" + params.save.imgName;
                console.log(path);
                var qr_svg = qr.image(params.string);
                var writer = nodeRequire('fs').createWriteStream(path);
                writer.on('finish', function(){
                    callback({status:true,path:path},{msg:''});
                });
                qr_svg.pipe(writer);

            };
            /** 测试代码 */
            /**
            baison_app.scanner.encode({
                type:'qr_image',
                string:'asdasdqweqwe你好',
                save:{imgName: "test.png"}
            },function(ret,err){
                console.log(ret);
            });
                */
            //网络类型 ==============================================================
            baison_app.api.connectionType = (function(){
                return (window.navigator.onLine==true)?"ethernet":"none";
            })();
            
            //应用名称和版本 =========================================================
            var data = nodeRequire('./package.json');
            baison_app.api.appName = data.name;
            baison_app.api.appVersion = data.version; 
            baison_app.api.systemVersion = os.release();
            
            //文件操作适配 ===========================================================
            baison_app.fs.exist = function(path,callback){
                if(path.path.indexOf('file://') != -1){
                    path.path = path.path.replace('file://','');
                }
                if(path.path.indexOf('/') != -1){
                    path.path = path.path.replace('/','\\');
                }
                
                fs.exists(path.path, function(exist){
                    var ret = {};
                    var err = {};
                    if(exist){
                        ret = {exist:true};
                        err = {err:""};
                    }else{
                        ret = {exist:false};
                        err = {err:"the file is not exist"};
                    }  
                    callback(ret,err);
                });
            };
            
            baison_app.fs.createFile = function(path, callback){
                if(path.path.indexOf('file://') != -1){
                    path.path = path.path.replace('file://','');
                }
                if(path.path.indexOf('fs://') != -1)  {
                    path.path = path.path.replace('fs://', baison_app.api.fsDir+'\\');
                }                      
                if(path.path.indexOf('/') != -1){
                    path.path = path.path.replace('/','\\');
                }
                fs.open(path.path,'w', function(error, fd){
                    var err = {};
                    var ret = {};
                    if(error){
                        err = {msg:error};
                    }else{
                        ret = {status:true};
                        fs.close(fd, function(err){
                            //console.log("文件关闭成功");
                        });
                    }
                    callback(ret, err);
                });
            };
            
            baison_app.fs.open = function(path,callback){
                fs.open(path.path,'r+', function(error, fd){
                    var err = {};
                    var ret = {};
                    if(error){
                        err = {msg:error};
                    }else{
                        ret = {status:true,fd:fd};
                    }
                    callback(ret, err);
                });
            };
            
            baison_app.fs.read = function(params,callback){
                var buf = new Buffer(100*1024*1024);
                buf.fill(0);
                fs.read(params.fd,buf,params.offset,buf.length,0, function(error, bytes){
                    var err = {};
                    var ret = {};
                    if(error){
                        err = {msg:error};
                    }else{
                        if(bytes > 0){
                            var data = buf.slice(0, bytes).toString();
                        }
                        ret = {status:true,data:data};
                        buf.fill(0);
                    }
                    callback(ret, err);
                });
            };
            
            baison_app.fs.remove = function(params,callback){
                if(params.path.indexOf('file://') != -1){
                    params.path = params.path.replace('file://','');
                }
                if(params.path.indexOf('fs://') != -1)  {
                    params.path = params.path.replace('fs://', baison_app.api.fsDir+'\\');
                }                      
                if(params.path.indexOf('/') != -1){
                    params.path = params.path.replace('/','\\');
                }
                fs.unlink(params.path,function(error){
                    var err = {};
                    var ret = {};
                    if(error){
                        err = {msg:error};
                    }else{
                        ret = {status:true};
                    }
                    callback(ret, err);
                });
            };
            
            //数据库操作适配 =============================================================
            baison_app.db.openDatabase = function(name,callback){
                db = new sqlite3.Database(__dirname+'\\'+name.name+'.db',function (err) {
                    var ret = {};
                    var error = {};
                    if (err) {
                        error = {msg:err.message};  
                        ret = {status:false};    
                    } else {
                        ret = {status:true};
                    } 
                    callback(ret, error);
                })
            };
            
            baison_app.db.executeSql = function(params, callback){
                // exec?
                db.run(params.sql, function(err){
                    var ret = {};
                    var error = {};
                    if (err) {
                        error = {msg:err.message};  
                        ret = {status:false};    
                    } else {
                        ret = {status:true};
                    } 
                    callback(ret, error);
                })
            };
            
            baison_app.db.selectSql = function(params, callback){
                db.all(params.sql, function(err, rows){
                    var ret ={};
                    var error = {};
                    if (err) {
                        error = {msg:err.message};  
                        ret = {status:false,data:rows};    
                    } else {
                        ret = {status:true,data:rows};
                    } 
                    callback(ret, error); 
                });
            };
            
            baison_app.db.transaction = function(trans,callback){
                //rollback?
                db.exec(trans.operation, function(err){
                    var ret ={};
                    var error = {};
                    if (err) {
                        error = {msg:err.message};  
                        ret = {status:false};    
                    } else {
                        ret = {status:true};
                    }
                    callback(ret, error); 
                });
            };
            
            //对话框控件适配 ==========================================================
            baison_app.api.alert = function(params){
                if(typeof params.msg == 'object'){
                    params.msg = JSON.stringify(params.msg);
                }
                
                dialog({
                    title: params.title,
                    content: params.msg,
                    width:200,
                    button: [
                        {
                            value: lang['ACT_CONFIRM'],
                            callback: function () {
                            },
                            autofocus: true
                        }
                    ]
                }).show();  
            }
            
            baison_app.api.toast = function(msg){
                var duration = 1500;
                if(msg.hasOwnProperty('duration')){
                    duration = msg.duration;
                }
                var d = dialog({
                    align: 'top',
                    follow: document.getElementById('toastFollow'),
                    content: msg.msg,
                    'zIndex':99999
                });
                d.width(200);
                d.show();
                setTimeout(function () {
                    d.close().remove();
                }, duration);
            }

            baison_app.api.helpPrompt = function(params){
                dialog({
                    id: params.id,
                    content: params.msg,
                    follow: document.getElementById(params.idfollow)
                }).show();
                dialog({id: params.id});  
            }

            
            baison_app.api.confirm = function(params, callback){
                dialog({
                    title: params.title,
                    content: params.msg,
                    button: [
                        {
                            value: lang['ACT_CONFIRM'],
                            callback: function () {
                                var ret = {buttonIndex:1};
                                var err = {}; 
                                callback(ret, err);
                            },
                            autofocus: true
                        },{
                            value: lang['ACT_CANCEL'],
                            callback: function () {
                                var ret = {buttonIndex:2}; 
                                var err = {};
                                callback(ret, err);
                            }
                        }
                    ]
                }).show();  
            }
            var progressDialog = dialog();
            baison_app.api.showProgress = function(params){                        
                progressDialog.title(params.title);
                progressDialog.width(200);
                progressDialog.show();
            }
            
            baison_app.api.hideProgress = function(){
                progressDialog.close();
            }
            
            baison_app.api.setScreenOrientation = function(){};
            
            //城市选择器模块=====================================================
            var city_win = null;
            var city_handler = function(data){};
            window.addEventListener('message',function(e){
                if(e.data.type == 'city'){
                    //console.log(e.data,city_handler);
                    city_handler(e.data.data);
                }
            });
            
            baison_app.citySelector.open = function(option, callback){
                city_win = window.open('file://' + __dirname + '/html/city.html','城市选择器');
                if(callback==undefined){
                    //console.log('城市选择器错误：回调函数未定义');
                }
                city_handler = callback;
            };
            
            baison_app.citySelector.close = function(){
                if(city_win){
                    city_win.close();
                }
            };
            
            //PC版本打印机适配 ======================================================
            baison_app.printmodule.getDevice = baison_app.usbPrint.getDevice = function(param, callback){
                var priner_info = printer.getPrinter();
                callback({name:priner_info.name},{});
            };
            
            baison_app.printmodule.printText = baison_app.usbPrint.printText = function(param, callback){
                printer.printDirect({
                    data: iconv.encode(param.text+'\r\n', 'GBK'),
                    type: 'RAW', // type: RAW, TEXT, PDF, JPEG, .. depends on platform
                    success:function(jobID){
                        callback({'status':true},{});
                        console.log("sent to printer with ID: "+jobID);
                    }, 
                    error:function(err){
                        callback({'status':false},err);
                        console.log(err);
                    }
                });
            };
            
            baison_app.printmodule.showBluetoothSetView = baison_app.usbPrint.showBluetoothSetView = function(param, callback){
                var priner_info = printer.getPrinter();
                callback({name:priner_info.name},{});
            };
            //打开外部浏览器 =======================================================
            baison_app.api.openApp = function(params,callback){
                if(params.mimeType=='text/html'){
                    shell.openExternal(params.uri);
                }
            };
            break;
        default:
            break;
    }
}else{
    var baison_app = {};
    
    var browser={ 
        versions:function(){
            var u = navigator.userAgent, app = navigator.appVersion; 
            return {//移动终端浏览器版本信息 
                trident: u.indexOf('Trident') > -1, //IE内核 
                presto: u.indexOf('Presto') > -1, //opera内核 
                webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核 
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核 
                mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端 
                ios: !!u.match(/i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 
                android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器 
                iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器 
                iPad: u.indexOf('iPad') > -1, //是否iPad 
                webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部 
            };
        }(),
        language:(navigator.browserLanguage || navigator.language).toLowerCase() 
    }
    
    if(browser.versions.mobile || browser.versions.ios || 
    browser.versions.android || browser.versions.iPhone || browser.versions.iPad){

    }else{
        
    }
    
    apiready = function () {
        //引用数据库和文件模块
        baison_app.db = api.require('db');
        baison_app.fs = api.require('fs');
        baison_app.scanner = api.require('scanner');
        baison_app.manager = api.require('downloadManager');
        baison_app.printmodule = api.require('modulePrint');
        baison_app.citySelector = api.require('citySelector');
		
        var systype = api.systemType;
        if (systype == 'ios') { //盒子支付 暂时支持ios
            if (window.navigator.onLine) {
                baison_app.boxPay = api.require('moduleBoxPay');
            }
            
        } else if (systype == 'android') {
            baison_app.usbPrint = api.require('usbprint');
			baison_app.feifanPrint = api.require('feifanPrint');//飞凡打印模块
			baison_app.feifanPay = api.require('feifanPay');//飞凡支付模块
        }

        //设置屏幕方向 ++++++++++++++++++++++++++++++++
        var xuanzhuan = $api.getStorage('configData').xuanzhuan;
        var xuanzhuan_str = '';
        if(xuanzhuan==1){
            xuanzhuan_str = 'landscape_right';
        }else{
            xuanzhuan_str = 'landscape_left';
        }
        api.setScreenOrientation({
            orientation: xuanzhuan_str
        });
        //设置全屏显示 ++++++++++++++++++++++++++++++++
        api.setFullScreen({
            fullScreen: true
        });

        baison_app.api = api;
		var simInfoImp = api.require('simInfoImp');
		simInfoImp.getDeviceId(function(ret) {
			baison_app.api.deviceId = ret.deviceId;
		});
        baison_app.api.helpPrompt = function(params){
            dialog({
                id: params.id,
                content: params.msg,
                follow: document.getElementById(params.idfollow)
            }).show();
            dialog({id: params.id});  
        }
    };
}